package com.threadpool.controller;

import com.threadpool.pool.CustomThreadFactory;
import com.threadpool.pool.CustomThreadPool;
import com.threadpool.pool.policy.DiscardOldestPolicy;
import com.threadpool.pool.policy.DiscardPolicy;
import com.threadpool.pool.queue.CustomBlockingQueue;
import com.threadpool.pool.queue.FixedCapacityQueue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author 桌角的眼镜
 */
@RestController
public class TaskController {

    private final CustomThreadPool threadPool;

    public TaskController() {
        this.threadPool = new CustomThreadPool(
                2,
                4,
                10,
                TimeUnit.SECONDS,
                new FixedCapacityQueue<>(5),
                new CustomThreadFactory(),
                new DiscardPolicy<>()
        );
    }

    @GetMapping("/submit")
    public String submitTask() {
        try {
            threadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName() + " 正在执行任务");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ignored) {
                }
            });
        } catch (Exception e) {
            return "任务被拒绝: " + e.getMessage();
        }
        return "任务提交成功";
    }
}